<template>
  <div class="staff">
    <div class="page_content">
      <div class="content_title"><span>运费设置</span></div>

      <el-row style="background: #fff;margin-bottom: 10px;">
        <el-col :span="22">
          <el-button type="primary" :loading="addLoading" @click="areaAdd">新增</el-button>
        </el-col>
      </el-row>

      <div v-for="(fareTemplate, index) in fareTemplateDetails" :key="index" class="detail_content">
        <div class="top_nav">
          <el-row>
            <el-col class="left" :span="6">
              <div>2020年02月10日 18:00 更新</div>
            </el-col>
            <el-col class="right" :span="18">
              <div class="total_bar">
                <el-button style="border: none;color:#1482F0;" @click.prevent="handleDelete(fareTemplate)"><span>删除</span></el-button>
              </div>
            </el-col>

          </el-row>
        </div>
        <div class="detail_body">
          <div class="item">
            <div><span>运费</span></div>
            <el-radio-group v-model="fareTemplate.type">
              <el-radio label="1" style="width: 50px;">
                包邮
              </el-radio>
              <el-radio label="2" style="width: 50px;">
                不销售
              </el-radio>
              <el-radio label="3">
                <el-input v-model="fareTemplate.money" :disabled="fareTemplate.type!=='3'" style="width: 90px; margin-right: 5px" placeholder="请输入内容" />元
              </el-radio>
            </el-radio-group>
          </div>
          <div style="margin-top: 10px;border: 1px solid #F1F1F1;padding: 10px;">
            <div style="margin-bottom: 10px;">对应区域</div>
            <div v-for="(area, indexA) in fareTemplate.areaList" :key="indexA">
              <el-checkbox v-model="area.checkAll" :disabled="area.disabled" class="el-checkbox-head" :indeterminate="area.isIndeterminate" @change="handleCheckAllChange($event, area, fareTemplate)">{{ areaName[indexA] }}</el-checkbox>
              <el-checkbox-group v-model="area.city" @change="checkOnly($event, area, fareTemplate)">
                <el-checkbox
                  v-for="(city,indexC) in area.areas"
                  :key="indexC"
                  :disabled="city.disabled"
                  :label="city.adcode"
                >
                  {{ city.name }}
                </el-checkbox>
              </el-checkbox-group>
              <div style="margin: 15px 0;" />
            </div>
          </div>
        </div>
      </div>

      <div class="page_foot padding_20">
        <div>
          <el-button type="primary" size="medium" :loading="saveLoading" @click="handleSubmit">保存</el-button>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import { fareTemplateDetails, area, areaAdd, areaEdit, areaDel } from '@/api/shop'
export default {
  data() {
    return {
      addLoading: false,
      saveLoading: false,
      fareTemplateDetails: [], // 运费模板集合
      detail: [],
      areaList: [],
      allchecked: [],
      areaName: ['华东', '华北', '华中', '华南', '东北', '西北', '西南', '港澳台', '海外'],
      fareTemplateObj: { fare_template_id: null, money: '', type: '1', city: [] } // 运费设置模板(新增时push用)
    }
  },
  created() {
    this.getFareTemplateDetails()
  },
  methods: {
    // 从组装的areaList里当前模板所有选中
    getTempCity(temp) {
      const areaList = temp.areaList
      const city = areaList.reduce((arr, areaCur) => {
        if (areaCur.city[0]) arr.push(...areaCur.city)
        return arr
      }, [])
      return city
    },
    // 当前城市设置选中时，其它模板里同个城市要禁用；不选中时其它模板才可设置
    setCityEnabled(adcodeArr, template) {
      // 获取所有选中
      const allSelected = this.fareTemplateDetails.reduce((arr, cur) => {
        // if(cur.city !== 0 && cur.city[0]) arr.push(...cur.city)
        const areaSelected = this.getTempCity(cur)
        // console.log(cur.fare_template_id, areaSelected)
        if (areaSelected[0]) arr.push(...areaSelected)
        return arr
      }, [])
      // console.log('adcodeArr', adcodeArr)
      // console.log('template', template)
      // console.log('allSelected', allSelected)
      this.fareTemplateDetails.forEach(tempItem => {
        // 找到其它模板
        if (tempItem.fare_template_id !== template.fare_template_id) {
          tempItem.areaList.forEach(area => {
            area.areas.forEach(item => {
              // 包含在被选中集合中
              if (adcodeArr.includes(item.adcode)) {
                this.$set(item, 'disabled', true)
              } else {
                // 不包含在当前区域选中集合中，而且不在当前所有选中列表中
                if (!allSelected.includes(item.adcode)) {
                  this.$set(item, 'disabled', false)
                }
              }
            })
            // 判断区域里的城市是否全部被禁用，如果是，则区域也会被禁用
            const disabledArr = area.areas.filter(item => item.disabled)
            this.$set(area, 'disabled', disabledArr.length === area.areas.length)
          })
        }
      })
    },
    // 区域全选效果
    handleCheckAllChange(val, area, template) {
      // console.log('val, area', val, area)
      // 选中时要排除掉禁用选项
      const unDisabled = area.areas.filter(item => !item.disabled).map(item => item.adcode)
      area.city = val ? unDisabled : []
      // console.log('unDisabled', unDisabled, area.areas)
      area.isIndeterminate = val ? unDisabled.length > 0 && unDisabled.length < area.areas.length : false
      // 设置其它模板不可选
      this.setCityEnabled(area.city, template)
    },
    // 单选选中事件
    checkOnly(val, area, template) {
      // console.log('val, area, template', val, area, template)
      // 设置当前区域组的全选效果
      const checkedCount = val.length
      const total = area.areas.length
      this.$set(area, 'checkAll', checkedCount === total)
      this.$set(area, 'isIndeterminate', checkedCount > 0 && checkedCount < total)
      // console.log('area', area)
      // 设置其它模板不可选
      this.setCityEnabled(val, template)
    },
    // 初始化时获取模板
    async getFareTemplateDetails() {
      const areaRes = await area()
      this.areaList = areaRes.detail.map(item => {
        return { areas: item, isIndeterminate: true, disabled: false }
      })
      // this.areaList.forEach(item => {
      //   this.$set(item, 'isIndeterminate', false)
      // })
      const fareTemplateRes = await fareTemplateDetails()
      // const checked = []
      this.fareTemplateDetails = fareTemplateRes.detail
      // 运费模板里加入区域列表
      this.$set(this.fareTemplateObj, 'areaList', JSON.parse(JSON.stringify(this.areaList)))
      this.fareTemplateDetails.forEach(item => {
        // 区域列表每组里选中数据
        this.areaList.forEach(area => {
          // 在城市列表里找到已经选中的
          let selectedCitys = []
          if (item.city !== 0 && item.city[0]) {
            selectedCitys = area.areas.filter(areaItem => item.city.includes(areaItem.adcode))
          }
          // 只取adcode
          if (selectedCitys[0]) {
            selectedCitys = selectedCitys.map(item => item.adcode)
          }
          // 当前组选中的code集合
          const selectedLen = selectedCitys.length
          this.$set(area, 'city', selectedCitys)
          this.$set(area, 'isIndeterminate', selectedLen > 0 && selectedLen < area.areas.length)
          // 可选code集合
          this.$set(area, 'cityOptions', area.areas.map(item => item.adcode))
        })
        // 每套模板加上区域列表
        this.$set(item, 'areaList', JSON.parse(JSON.stringify(this.areaList)))
      })
      this.fareTemplateDetails.forEach(item => {
        // 禁用其它模板相同选项
        if (item.city !== 0 && item.city[0]) this.setCityEnabled(item.city, item)
      })
      console.log('模板集合', this.fareTemplateDetails)
    },
    // 新增模板
    areaAdd() {
      this.addLoading = true
      areaAdd({}).then(res => {
        // 重新初始化
        this.getFareTemplateDetails()
        this.addLoading = false
      })
    },
    // 删除模板
    handleDelete(temp) {
      // 前端删除模板
      console.log('temp', temp)
      console.log('fareTemplateDetails', this.fareTemplateDetails)
      this.$confirm('此操作将删除这个运费模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // this.fareTemplateDetails = this.fareTemplateDetails.filter(item => item.fare_template_id !== temp.fare_template_id)
        const res = await areaDel({ fare_template_id: temp.fare_template_id })
        this.$notify({
          title: '提示',
          type: res.code === 1001 ? 'success' : 'error',
          message: res.msg,
          position: 'bottom-right'
        })
        this.getFareTemplateDetails()
      }).catch(_ => {})
    },
    // 保存(遍历单个保存)
    handleSubmit() {
      // 循环发请求
      this.saveLoading = true
      this.fareTemplateDetails.forEach(async(temp) => {
        // 更新city
        temp.city = this.getTempCity(temp)
        console.log(temp.fare_template_id, temp.city)
        const res = await areaEdit({
          fare_template_id: temp.fare_template_id,
          type: temp.type,
          money: temp.money,
          city: temp.city.join()
        })
        this.$notify({
          title: '提示',
          type: res.code === 1001 ? 'success' : 'error',
          message: res.msg,
          position: 'bottom-right'
        })
      })
      this.saveLoading = false
      this.getFareTemplateDetails()
    }
  }
}
</script>

<style lang="less" scoped>
.staff{
	padding: 20px;
	min-height: 100%;
	.page_content{
		padding: 20px;
		background:#fff;
		.el-row{
			.el-button{
				min-width: 120px;
			}
		}
		.content_title{
			font-size: 16px;
			font-weight: 600;
			padding-bottom: 20px;
		}

		.detail_content{
			.top_nav{
				margin: 10px 0 20px 0;
				.left{
					font-size: 14px;
					color: #ccc;
					height: 40px;
					display: flex;
					align-items: center;
					justify-content: center;
					border: 1px solid #ccc;
					border-bottom: none;
				}
				.right{
					height: 40px;
					display: flex;
					align-items: center;
					justify-content: flex-end;
					border-bottom: 1px solid #ccc;
				}
			}
			.detail_body{
				padding-left: 10px;
				.item{
					margin: 10px 0;
				}
			}
		}

		.page_foot{
			display: flex;
			justify-content: flex-start;
			padding: 20px 10px;
		}

	}

}
</style>
